package com.ruoyi.base.redis.dept;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.platform.system.dept.dao.DeptDAO;
import com.ruoyi.platform.system.dept.pojo.DeptDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 部门redis
 *
 * @author lcf
 */
@Component
public class DeptRedis {

    @Autowired
    private DeptDAO deptDAO;
    @Autowired
    public StringRedisTemplate redisTemplate;

    /**
     * 过期时间
     */
    private int timeout = 1;

    /**
     * 过期时间单位
     */
    private TimeUnit timeUnit = TimeUnit.HOURS;

    /**
     * 部门key
     */
    private final String key = "dept";

    /**
     * 删除
     */
    public void delete() {
        redisTemplate.delete(key);
    }

    /**
     * 缓存
     */
    public void cache() {
        List<DeptDO> list = deptDAO.selectByDept(null);
        redisTemplate.boundValueOps(key).set(JSON.toJSONString(list), timeout, timeUnit);
    }

    /**
     * 获取部门
     */
    public List<DeptDO> getDeptList() {
        String json = redisTemplate.boundValueOps(key).get();
        if (json != null) {
            return JSON.parseArray(json, DeptDO.class);
        }

        List<DeptDO> list = deptDAO.selectByDept(null);
        redisTemplate.boundValueOps(key).set(JSON.toJSONString(list), timeout, timeUnit);
        return list;
    }
}
